package br.com.puertorico.mecanismos.ui.converters;

import java.math.BigDecimal;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.NumberConverter;

import br.com.puertorico.common.utils.Formatador;

/**
 * Respons&aacute;vel pela conver&ccedil;&atilde;o de um valor do tipo moeda.
 *
 * @author <a href="mailto:daniel.camargo@ufms.br">Daniel Camargo</a>
 * @version $id$
 */
public class MoedaConverter extends NumberConverter {

	/**
	 * Construtor da classe MoedaConverter.
	 */
	public MoedaConverter() {
		super();
		super.setLocale(Formatador.getLocaleBrasil());
		super.setCurrencySymbol("R$");
	}

	/**
	 * {@inheritDoc}
	 */
	public Object getAsObject(FacesContext context, UIComponent component,
			String string) {
		Object value = super.getAsObject(context, component, string);

		if (value instanceof Long) {
			return BigDecimal.valueOf((Long) value);
		}
		if (value instanceof Double) {
			return BigDecimal.valueOf((Double) value);
		}
		if (value instanceof BigDecimal) {
			return ((BigDecimal) value).doubleValue();
		}
		return value;
	}

	/**
	 * {@inheritDoc}
	 */
	public String getAsString(FacesContext ctx, UIComponent ui, Object value) {
		if (value == null) {
			return null;
		}
		if (value instanceof Double) {
			return Formatador.formatarMoeda(new BigDecimal((Double) value));
		} else {
			return Formatador.formatarMoeda((BigDecimal) value);
		}
	}
}
